#!/bin/bash
git=${GIT:-/usr/bin/git}
args=$@
if [[ $1 != "clone" ]]; then
  $git "$@"
  exit
fi
until [ -z $1 ]
do
  if [[ $1 == "https://github.com/"* ]]; then
    break
  fi
  shift
done

if [ -z $1 ]; then
  $git $args
  exit
fi
repo_group=`echo $1 | cut -d / -f 4`
repo_name=`echo $1 | cut -d / -f 5`
repo_name=${repo_name%".git"}
shift
if [[ $1 != "" ]]; then
  target=$1
else
  target=$repo_name
fi
if [[ $target == "" || $target == "*" ]]; then
  echo "repo target '$target' is invalid"
  exit 1
fi
if [ -d "$target" ]; then
  echo "fatal: destination path '$target' already exists and is not an empty directory."
  exit 128
fi
go install github.com/$repo_group/$repo_name@latest
# for MacOS, sed doesn't support \L, need to install gnu version: brew install gnu-sed, and then insert to PATH
group_dir=`echo $repo_group | sed 's/[A-Z]/!\L&/g'`
group_dir=~/go/pkg/mod/github.com/$group_dir
name_dir=`echo $repo_name | sed 's/[A-Z]/!\L&/g'`
name_dir=`ls -tr $group_dir | grep "${name_dir}@" | tail -1`
from_dir=$group_dir/$name_dir
chmod -R u+rw $from_dir
target_dir=`dirname $target`
if [ ! -d $target_dir ]; then
  mkdir -p $target_dir
fi
echo "cp -r $from_dir $target"
cp -r $from_dir $target
cd $target
git init
git add .
git commit -m 'init'
git remote add origin https://github.com/$repo_group/$repo_name.git
if [ -d 'bin' ]; then
  chmod -R a+x bin
fi
